package ws.db.execsql;

import ws.db.*;
import ws.db.sql.SQLInterface;
import ws.log.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;



public class ExecSQL extends DBOpenClose {
	
	/**
	 * Execute one sql command.
	 * @param:
	 * 		sql - the SQLInterface.
	 * @return:
	 * 		int - the affected rows. if -1 the error.
	 * @exception:
	 * 		exception has been written to log file.
	 * */
	public int execOneCommand(SQLInterface sql){
		
		String sqlcommand = sql.getSQL();
		int result = -1 ;
		Connection conn  = null;
		Statement stmt =null;
		try{
			conn = getConn();
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			result = stmt.executeUpdate(sqlcommand);
			conn.commit();
		}catch(Exception e){
		//	System.out.print(e.getMessage());
			Log.writeDBMiddleLayerLog("执行单条语句错误:"+sqlcommand, e);
			try{
				conn.rollback();
			}catch(SQLException ex){
				//System.out.print(ex.getMessage());
				Log.writeDBMiddleLayerLog("执行单条语句失败，回滚错误", ex);
			}
			
		}finally{
			close(conn,stmt,null);
		}
		return result;
	}
	
	/**
	 * Execute batch sql commands.
	 * @param:
	 * 		sqls - the ArrayList<SQLInterface> contains several SQLInterface object.
	 * @return:
	 * 		int[] - Because there are many commands have been executed,then need to return a array.
	 * @exception:
	 * 		exception has been written to log file.
	 * */
	public int[] execBatchCommand(ArrayList<SQLInterface> sqls){
		int [] result = null;
		Connection conn = null;
		Statement stmt = null;
		
		try{
			conn = getConn();
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			Iterator its = sqls.iterator();
			while(its.hasNext()){
				SQLInterface eachsql = (SQLInterface)its.next();
				stmt.addBatch(eachsql.getSQL());
			}
			result = stmt.executeBatch();
			conn.commit();
		}catch(Exception e){
		///	System.out.print(e.getMessage());
			
			StringBuffer sqlbuf = new StringBuffer();
			Iterator its = sqls.iterator();
			while(its.hasNext()){
				SQLInterface eachsql = (SQLInterface)its.next();
				sqlbuf.append(eachsql.getSQL()+"\r\n");
			}
			Log.writeDBMiddleLayerLog("执行多条语句错误"+sqlbuf.toString(),e);
			try{
				conn.rollback();
			}catch(SQLException ex){
				//System.out.print(ex.getMessage());
				Log.writeDBMiddleLayerLog("执行多条语句失败，回滚错误", ex);
			}
			
		}finally{
			close(conn,stmt,null);
		}
		return result;
	}
	
}
